/**
 * @file yuv7.c
 * @author your name (you@domain.com)
 * @brief  PSNR是最基本的视频质量评价方法。本程序中的函数可以对比两张YUV图片中亮度分量Y的PSNR。
 * @version 0.1
 * @date 2021-04-27
 * 
 * @copyright Copyright (c) 2021
 * 
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int simplest_yuv420_psnr(char *url1,char *url2,int w,int h,int num);

int main(void)
{
    simplest_yuv420_psnr("../resource/lena_256x256_yuv420p.yuv","../resource/lena_distort_256x256_yuv420p.yuv",256,256,1);
    return 0;
}

int simplest_yuv420_psnr(char *url1,char *url2,int w,int h,int num)
{
    FILE * fp1 = fopen(url1, "rb+");
    if(fp1 == NULL) {
        printf("fopen[%s]\n", strerror(errno));
        return -1;
    }
    FILE * fp2 = fopen(url2, "rb+");
    if(fp2 == NULL) {
        printf("fopen[%s]\n", strerror(errno));
        return -1;
    }
    uint8_t * pic1 = (uint8_t*) malloc(w * h);
    uint8_t * pic2 = (uint8_t*) malloc(w * h);

    for (int i = 0; i < num; i++)
    {
        fread(pic1, 1, w * h, fp1);
        fread(pic2, 1, w*h, fp2);

        double mse_sum = 0, mse = 0, psnr = 0;
        
        /* 使用一定的数学公式计算而得 */
        for (int j = 0; j < w *h; j++)
        {
            mse_sum = pow((double)(pic1[j] - pic2[j]),2);
        }

        mse = mse_sum / (w * h);
        psnr = 10 * log10(255.0 * 255.0 / mse);
        printf("%5.3f\n", psnr);

        //转移到下一个Y 分量的位置
        fseek(fp1, w* h /2,SEEK_CUR);
        fseek(fp2, w * h / 2, SEEK_CUR);
    }

    free(pic1);
    free(pic2);

    fclose(fp1);
    fclose(fp2);

    return 0;
}